package com.yesep.learn.mqtt.client.session;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.yesep.learn.mqtt.client.common.MqttOption;

/**
 * 
 * @Description:
 */
public final class SessionManager {

	private static final ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();

	private SessionManager() {
	}

	public static <K, V> Session<K, V> init(MqttOption option) {

		Session<K, V> s;
		try {
			s = option.session().newInstance();
		} catch (InstantiationException | IllegalAccessException | NullPointerException e) {
			// default
			s = new MemorySession<K, V>();
		}
		return sessionMap.putIfAbsent(option.clientId(), s);
	}

	/**
	 * 获取已存在的Session
	 * <p>
	 * 不存在则为当前 {@code clientId} 创建一个{@code Session}
	 * <p>
	 * 默认使用{@link MemorySession}
	 *
	 * @param clientId clientId
	 * @return Session
	 */
	public static <K, V> Session<K, V> getSession(String clientId) {
		return sessionMap.get(clientId);
	}

	/**
	 * 清除Session
	 *
	 * @param clientId clientId
	 */
	public static <K, V> Session<K, V> removeSession(String clientId) {
		return sessionMap.remove(clientId);
	}

}
